package com.jastar.android.test.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.jastar.android.test.MyApplication;
import com.jastar.android.test.R;
import com.jastar.android.test.base.room.dao.BookInfoDao;
import com.jastar.android.test.base.room.entity.BookInfo;
import com.jastar.android.util.Alert;
import com.jastar.android.util.FileUtil;

import java.io.File;

/**
 * 数据存储
 */
public class StorageActivity extends AppCompatActivity implements View.OnClickListener {

    private SharedPreferences preferences;
    private String databaseName;
    private ImageView iv_local;
    private BookInfoDao bookInfoDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage);

        super.findViewById(R.id.button_1).setOnClickListener(this);
        super.findViewById(R.id.button_2_1).setOnClickListener(this);
        super.findViewById(R.id.button_2_2).setOnClickListener(this);
        super.findViewById(R.id.button_3).setOnClickListener(this);
        super.findViewById(R.id.button_4).setOnClickListener(this);
        super.findViewById(R.id.button_5).setOnClickListener(this);
        super.findViewById(R.id.button_6).setOnClickListener(this);

        iv_local = super.findViewById(R.id.iv_local);
        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        databaseName = getFilesDir() + "/test.db";
        bookInfoDao = MyApplication.getInstance().getBookDatabase().bookInfoDao();

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_1) {

            String content = saveAndReadSharedPreferences("name", "保存在SharedPreferences的数据");
            Toast.makeText(this, "读取到信息：" + content, Toast.LENGTH_SHORT).show();

        } else if (v.getId() == R.id.button_2_1) {

            SQLiteDatabase database = openOrCreateDatabase(databaseName, Context.MODE_PRIVATE, null);
            Toast.makeText(this, "创建成功：" + database.getPath(), Toast.LENGTH_SHORT).show();

        } else if (v.getId() == R.id.button_2_2) {

            boolean result = deleteDatabase(databaseName);
            Toast.makeText(this, "删除结果：" + result, Toast.LENGTH_SHORT).show();

        } else if (v.getId() == R.id.button_3) {

            saveToFile("测试内容.");

        } else if (v.getId() == R.id.button_4) {

            String path = saveImage();
            loadImage(path);

        } else if (v.getId() == R.id.button_5) {

            String key = "KEY", value = "Application存储";
            MyApplication.getInstance().put(key, value);
            String res = MyApplication.getInstance().get(key);
            Alert.toast(this, "读取到信息：" + res);

        } else if (v.getId() == R.id.button_6) {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setName("哪吒");
            bookInfoDao.insert(bookInfo);
            BookInfo entity = bookInfoDao.queryOneByName("哪吒");
            Alert.toast(this, "查询到书籍：" + entity);

        }

    }

    /**
     * SharedPreferences保存和读取
     * 保存路径：/data/data/应用包名/shared_prefs/文件名.xml
     */
    private String saveAndReadSharedPreferences(String key, String value) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.apply();

        return preferences.getString(key, null);
    }

    /**
     * 存储到文本文件
     * ************************************************
     * 三个位置可选：
     * //内部存储私有空间(卸载APP后清除，空间有限)
     * getFilesDir()
     * //外部存储的私有空间(卸载APP后清除)
     * getExternalFilesDir()
     * //外部存储的公共空间(卸载APP后保留)，使用前需要在AndroidManifest.xml开启配置，并需要用户开启授权
     * Environment.getExternalStoragePublicDirectory()
     */
    private void saveToFile(String text) {
        String fileName = "文本文件存储.txt";

        String dir = getFilesDir().toString();
        //String dir = String.valueOf(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS));
        //String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();

        String path = dir + File.separatorChar + fileName;
        FileUtil.saveText(path, text);
        Toast.makeText(this, "保存成功：" + path, Toast.LENGTH_SHORT).show();
    }


    private String saveImage() {
        String fileName = System.currentTimeMillis() + ".jpg";
        //获取当前APP的私有下载目录
        String downloadPath = String.valueOf(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS));
        String path = downloadPath + File.pathSeparatorChar + fileName;
        //从指定资源文件获取位图对象
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic_expression_smile);
        //把位图保存在图片文件
        FileUtil.saveImage(path, bitmap);
        bitmap.recycle();
        Alert.toast(this, "保存成功!");
        return path;
    }

    private void loadImage(String path) {
        //方式一
        //Bitmap bitmap = FileUtil.openImage(path);
        //iv_local.setImageBitmap(bitmap);

        //方式二
        //Bitmap bitmap = BitmapFactory.decodeFile(path);
        //iv_local.setImageBitmap(bitmap);

        //方式三
        iv_local.setImageURI(Uri.parse(path));
    }

}